<template>
  <div>
    <!-- 页面标题显示当前合集ID -->
    <div class="page-title">
      <h2>章节管理 - 合集ID: {{ setId }}</h2>
    </div>
    <!-- 查询表单 -->
    <el-form inline :model="sectionQuery" class="query-form">
      <el-form-item label="章节标题">
        <el-input v-model="sectionQuery.title" placeholder="请输入章节标题" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getSectionPage" icon="Search">查询</el-button>
        <el-button @click="resetQuery" icon="RefreshRight">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作按钮 -->
    <el-button @click="openAddDialog" type="primary" icon="Plus" class="add-btn">新增章节</el-button>
    <!-- 章节表格 -->
    <el-table :data="sectionPage.list" border stripe v-loading="loading">
      <el-table-column label="章节ID" prop="sectionId"></el-table-column>
      <el-table-column label="章节标题" prop="title"></el-table-column>
      <el-table-column label="章节描述" prop="description"></el-table-column>
      <el-table-column label="排序序号" prop="sequence"></el-table-column>
      <el-table-column label="关联视频" prop="videos">
        <template v-slot="scope">
          <el-popover
              placement="top"
              title="已关联视频"
              :width="400"
              trigger="hover"
          >
            <template #reference>
              <div class="video-tag-container">
                <el-tag type="info" v-if="scope.row.videos && scope.row.videos.length">
                  {{ scope.row.videos.length }}个视频
                </el-tag>
                <el-tag type="warning" v-else>未关联视频</el-tag>
              </div>
            </template>
            <!-- 用 el-table 替代 el-list 展示已关联视频 -->
            <el-table
                :data="scope.row.videos || []"
                border
                size="small"
                :show-header="false"
            >
              <el-table-column prop="title" label="视频标题" width="200"></el-table-column>
              <el-table-column prop="videoId" label="视频ID" width="150"></el-table-column>
            </el-table>
            <template v-if="!(scope.row.videos && scope.row.videos.length)">
              <div class="no-video">未关联任何视频</div>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createdTime">
        <template v-slot="scope">
          {{ formatDateTime(scope.row.createdTime) }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" prop="updatedTime">
        <template v-slot="scope">
          {{ formatDateTime(scope.row.updatedTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260">
        <template v-slot="scope">
          <el-space>
            <el-button size="small" type="primary" @click="openEditDialog(scope.row)" icon="Edit">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteSection(scope.row)" icon="Delete">删除</el-button>
            <el-dropdown>
              <el-button size="small">
                更多
                <el-icon class="el-icon--right">
                  <arrow-down/>
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item size="small" @click="moveSection(scope.row, 'up')" icon="ArrowUp"
                                    :disabled="scope.$index === 0">上移
                  </el-dropdown-item>
                  <el-dropdown-item size="small" @click="moveSection(scope.row, 'down')" icon="ArrowDown"
                                    :disabled="scope.$index === sectionPage.list.length - 1">下移
                  </el-dropdown-item>
                  <el-dropdown-item size="small" @click="openVideoManagerDialog(scope.row)" icon="VideoCamera">视频管理
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-space>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页控件 -->
    <el-pagination
        v-model:current-page="sectionQuery.pageNum"
        v-model:page-size="sectionQuery.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="sectionPage.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 15px; text-align: right"
    />

    <!-- 新增/编辑章节对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEditing ? '编辑章节' : '新增章节'"
        width="600px"
    >
      <el-form :model="sectionForm" ref="formRef" label-width="100px" :rules="formRules">
        <el-form-item label="章节标题" prop="title">
          <el-input v-model="sectionForm.title" placeholder="请输入章节标题" clearable></el-input>
        </el-form-item>
        <el-form-item label="章节描述" prop="description">
          <el-input
              v-model="sectionForm.description"
              placeholder="请输入章节描述"
              type="textarea"
              :rows="4"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序序号" prop="sequence">
          <el-input-number
              v-model="sectionForm.sequence"
              :min="1"
              placeholder="请输入排序序号"
          ></el-input-number>
          <div class="form-hint">序号越小，显示位置越靠前</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 多视频管理对话框 -->
    <el-dialog
        v-model="videoManagerVisible"
        title="管理章节视频"
        width="900px"
        :before-close="handleVideoManagerClose"
    >
      <div class="video-manager-container">
        <!-- 已关联视频列表 -->
        <div class="video-list-container">
          <div class="video-list-header">
            <h3>已关联视频 ({{ relatedVideos.length }})</h3>
            <el-button
                size="small"
                @click="clearAllRelations"
                :disabled="relatedVideos.length === 0"
            >
              全部移除
            </el-button>
          </div>
          <el-table
              :data="relatedVideos"
              border
              size="small"
              :row-key="(row) => row.videoId"
          >
          >
            <el-table-column label="序号" type="index" width="50"></el-table-column>
            <el-table-column label="视频标题" prop="title" width="200"></el-table-column>
            <el-table-column label="视频ID" prop="videoId" width="180"></el-table-column>
            <el-table-column label="时长(秒)" prop="duration"></el-table-column>
            <el-table-column label="上传时间" prop="uploadTime">
              <template v-slot="scope">
                {{ formatDateTime(scope.row.uploadTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template v-slot="scope">
                <el-button
                    size="small"
                    type="danger"
                    icon="Delete"
                    @click="removeVideoRelation(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="video-sort-controls" v-if="relatedVideos.length > 1">
            <span>调整顺序：</span>
            <el-button
                size="small"
                icon="ArrowUp"
                @click="moveVideo('up')"
            ></el-button>
            <el-button
                size="small"
                icon="ArrowDown"
                @click="moveVideo('down')"
            ></el-button>
            <el-button
                size="small"
                type="primary"
                @click="saveVideoOrder"
            >
              保存顺序
            </el-button>
          </div>
        </div>
        <!-- 视频选择区 -->
        <div class="video-separator">
          <el-icon class="transfer-icon">
            <arrow-right/>
          </el-icon>
          <el-icon class="transfer-icon">
            <arrow-left/>
          </el-icon>
        </div>
        <!-- 可选视频列表 -->
        <div class="video-list-container">
          <div class="video-list-header">
            <h3>可选视频库</h3>
            <el-space>
              <el-input
                  v-model="videoQuery.title"
                  placeholder="搜索视频"
                  clearable
                  size="small"
                  @keyup.enter="getAvailableVideos"
              ></el-input>
              <el-button
                  size="small"
                  type="primary"
                  icon="Search"
                  @click="getAvailableVideos"
              ></el-button>
            </el-space>
          </div>
          <el-table
              :data="availableVideos"
              border
              ref="waitRelateTableRef"
              size="small"
              :row-key="(row) => row.videoId"
              @selection-change="handleVideoSelectionChange"
              v-loading="videoLoading"
          >
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column label="视频标题" prop="title" width="200"></el-table-column>
            <el-table-column label="视频ID" prop="videoId" width="180"></el-table-column>
            <el-table-column label="时长(秒)" prop="duration"></el-table-column>
            <el-table-column label="上传时间" prop="uploadTime">
              <template v-slot="scope">
                {{ formatDateTime(scope.row.uploadTime) }}
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              v-model:current-page="videoQuery.pageNum"
              v-model:page-size="videoQuery.pageSize"
              :page-sizes="[5, 10, 20]"
              background
              layout="total, sizes, prev, pager, next"
              :total="availableVideosTotal"
              @size-change="handleVideoPageSizeChange"
              @current-change="handleVideoPageChange"
              size="small"
              style="margin-top: 10px; text-align: right"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="videoManagerVisible = false">取消</el-button>
          <el-button
              type="primary"
              @click="confirmVideoRelations"
              :loading="savingRelations"
          >
            确认关联
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, watch, computed} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage, ElMessageBox, FormInstance} from 'element-plus'
import {
  reqGetSectionPage,
  reqCreateSection,
  reqUpdateSection,
  reqDeleteSection,
  reqAdjustSectionOrder,
  reqGetAvailableVideos,
  reqBatchRelateVideos,
  reqUpdateVideoOrder,
  reqDeleteSectionVideo, reqBatchDelRelateVideosByIds , reqGetSectionRelatedVideoList
} from '@/api/share/section'
import {reqGetNotRelatedVideoPage} from "@/api/share";

// 路由相关
const route = useRoute()
const router = useRouter()
const setId = computed(() => route.query.setId as string)

// 对话框状态
const dialogVisible = ref(false)
const isEditing = ref(false)
const formRef = ref<FormInstance>()

// 查询参数
const sectionQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  title: '',
  setId: '' // 由路由参数填充
})
// 表格数据
const sectionPage = reactive({
  total: 0,
  list: [],
  pageNum: 1,
})
let loading = ref(true)

// 表单数据
const sectionForm = reactive({
  sectionId: null,
  setId: '',
  title: '',
  description: '',
  sequence: 1
})

// 表单验证规则
const formRules = reactive({
  title: [
    {required: true, message: '请输入章节标题', trigger: 'blur'},
    {max: 100, message: '标题长度不能超过100个字符', trigger: 'blur'}
  ],
  sequence: [
    {required: true, message: '请输入排序序号', trigger: 'blur'}
  ]
})
// 视频管理对话框状态
const videoManagerVisible = ref(false)//弹窗状态
const currentEditingSection = ref<any>(null)//当前选择的合集信息
const savingRelations = ref(false)//按钮loading

// 已关联视频列表
const relatedVideos = ref<any[]>([])
// 待添加的视频
const pendingAddVideos = ref<any[]>([])
let waitRelateTableRef = ref()

// 可选视频查询参数
const videoQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  title: '',
})

// 可选视频列表数据
const availableVideos = ref<any[]>([])
const availableVideosTotal = ref(0)
const videoLoading = ref(false)

// 获取章节列表
const getSectionPage = async () => {
  try {
    sectionQuery.setId = setId.value
    const res = await reqGetSectionPage(sectionQuery)
    Object.assign(sectionPage, res.data)
    loading.value = false
  } catch (error) {
    ElMessage.error('获取章节列表失败')
    console.error(error)
  }
}

// 重置查询条件
const resetQuery = () => {
  sectionQuery.title = ''
  sectionQuery.pageNum = 1
  getSectionPage()
}

// 打开新增对话框
const openAddDialog = () => {
  isEditing.value = false
  // 重置表单
  Object.assign(sectionForm, {
    sectionId: null,
    setId: setId.value,
    title: '',
    description: '',
    sequence: sectionPage.list.length + 1 // 默认序号为最后一位
  })
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (row: any) => {
  isEditing.value = true
  Object.assign(sectionForm, row)
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    if (isEditing.value) {
      // 编辑操作
      await reqUpdateSection(sectionForm)
    } else {
      // 新增操作
      await reqCreateSection(sectionForm)
    }
    dialogVisible.value = false
    getSectionPage()
  } catch (error) {
    console.error('表单验证失败或提交出错', error)
    return
  }
}

// 删除章节
const deleteSection = (row: any) => {
  ElMessageBox.confirm(
      `确定要删除章节"${row.title}"吗？删除后不可恢复。`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      } as string
  )
      .then(async () => {
        try {
          await reqDeleteSection(row.sectionId)
          ElMessage.success('删除章节成功')
          getSectionPage()
        } catch (error) {
          ElMessage.error('删除章节失败')
          console.error(error)
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
}

// 调整章节顺序
const moveSection = async (row: any, direction: 'up' | 'down') => {
  try {
    await reqAdjustSectionOrder({
      sectionId: row.sectionId,
      setId: setId.value,
      direction: direction === 'up' ? 1 : 2 // 1表示上移，2表示下移
    })
    getSectionPage()
  } catch (error) {
    console.error(error)
  }
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  // 简单格式化，实际项目中可使用dayjs等库
  return new Date(dateTime).toLocaleString()
}

// 分页事件处理
const handleSizeChange = (val: number) => {
  sectionQuery.pageSize = val
  getSectionPage()
}

const handleCurrentChange = (val: number) => {
  sectionQuery.pageNum = val
  getSectionPage()
}

// 监听路由参数变化
watch(setId, (newVal) => {
  if (newVal) {
    sectionQuery.setId = newVal
    getSectionPage()
  }
})
// 打开视频管理对话框
const openVideoManagerDialog = async (row: any) => {
  currentEditingSection.value = {...row}
  // 初始化已关联视频
  let res = await reqGetSectionRelatedVideoList(row.sectionId)
  relatedVideos.value = res.data
  videoManagerVisible.value = true
  // 加载可选视频
  videoQuery.pageNum = 1
  getAvailableVideos()
}

const getAvailableVideos = async () => {
  try {
    videoLoading.value = true
    const res = await reqGetNotRelatedVideoPage(videoQuery)
    availableVideos.value = res.data.list
    availableVideosTotal.value = res.data.total
  } catch (error) {
    console.error(error)
  } finally {
    videoLoading.value = false
  }
}

// 处理视频选择
const handleVideoSelectionChange = (selection: any[]) => {
  pendingAddVideos.value = selection
}

// 移除单个视频关联
const removeVideoRelation = async (video: any) => {
  // 刷新可选视频列表，被移除的视频可以重新被选择
  ElMessageBox.confirm(`删除之后无法恢复，确认删除关联${video.videoId}吗？`,'警告',{
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  } as string).then(async () => {
    await reqBatchDelRelateVideosByIds([video.sectionVideoId])
    getAvailableVideos()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}
// 清除所有关联
const clearAllRelations = () => {
  ElMessageBox.confirm(
      '确定要移除所有已关联的视频吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      } as string
  ).then(() => {
    reqBatchDelRelateVideosByIds(relatedVideos.value.map(v => v.sectionVideoId))
    getAvailableVideos()
  })
}

// 调整视频顺序
const moveVideo = (direction: 'up' | 'down') => {
  // 找到选中的视频索引
  const selectedIndex = relatedVideos.value.findIndex(v => v._selected)

  if (selectedIndex === -1) {
    ElMessage.warning('请先选中一个视频')
    return
  }

  // 检查边界
  if (direction === 'up' && selectedIndex === 0) {
    ElMessage.warning('已经是第一个视频了')
    return
  }

  if (direction === 'down' && selectedIndex === relatedVideos.value.length - 1) {
    ElMessage.warning('已经是最后一个视频了')
    return
  }

  // 交换位置
  const newIndex = direction === 'up' ? selectedIndex - 1 : selectedIndex + 1
  const temp = relatedVideos.value[selectedIndex]
  relatedVideos.value[selectedIndex] = relatedVideos.value[newIndex]
  relatedVideos.value[newIndex] = temp

  // 更新选中状态
  relatedVideos.value.forEach((v, i) => {
    v._selected = i === newIndex
  })
}

// 保存视频顺序
const saveVideoOrder = async () => {
  try {
    await reqUpdateVideoOrder({
      sectionId: currentEditingSection.value.sectionId,
      videoIds: relatedVideos.value.map(v => v.videoId)
    })
  } catch (error) {
    console.error(error)
  }
}

// 确认视频关联
const confirmVideoRelations = async () => {
  if (!currentEditingSection.value) return
  try {
    savingRelations.value = true
    // 调用API保存视频关联
    await reqBatchRelateVideos({
      sectionId: currentEditingSection.value.sectionId,
      videoIds: pendingAddVideos.value.map(v => v.videoId)
    })
    videoManagerVisible.value = false
    // 刷新章节列表
    getSectionPage()
  } catch (error) {
    ElMessage.error('更新视频关联失败')
    console.error(error)
  } finally {
    savingRelations.value = false
  }
}

// 处理视频管理对话框关闭
const handleVideoManagerClose = () => {
  pendingAddVideos.value = []
  videoManagerVisible.value = false
}

// 视频分页事件处理
const handleVideoPageSizeChange = (val: number) => {
  videoQuery.pageSize = val
  getAvailableVideos()
}

const handleVideoPageChange = (val: number) => {
  videoQuery.pageNum = val
  getAvailableVideos()
}

// 页面加载时获取数据
onMounted(() => {
  if (setId.value) {
    sectionQuery.setId = setId.value
    getSectionPage()
  } else {
    ElMessage.warning('未获取到合集ID，请从合集管理页面进入')
    // 延时返回，避免弹窗被导航覆盖
    setTimeout(() => {
      router.back()
    }, 1000)
  }
})
</script>

<style scoped>
.page-title {
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.query-form {
  margin-bottom: 15px;
}

.add-btn {
  margin-bottom: 15px;
}

.form-hint {
  margin-top: 5px;
  font-size: 12px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
